package uno.linze.interview_question.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import uno.linze.interview_question.dto.QuestionDTO;
import uno.linze.interview_question.dto.PagedResponse;
import uno.linze.interview_question.service.QuestionService;
import uno.linze.interview_question.util.base.ApiResponse;

@RestController
@RequestMapping("/api/v1")
@Tag(name = "题目与审核模块", description = "题目的管理与查询接口")
public class QuestionController {
    @Autowired
    private QuestionService questionService;

    @GetMapping("/question")
    @Operation(summary = "查询题目列表", description = "获取题目列表，支持多条件筛选")
    public ApiResponse<PagedResponse<QuestionDTO>> getQuestionList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "20") Integer size,
            @Parameter(description = "分类ID筛选") @RequestParam(required = false) Integer categoryId,
            @Parameter(description = "难度等级筛选（1:简单, 2:中等, 3:困难）") @RequestParam(required = false) Integer difficulty,
            @Parameter(description = "标签ID筛选") @RequestParam(required = false) Integer tagId,
            @Parameter(description = "标题搜索关键词") @RequestParam(required = false) String keyword
    ) {
        PagedResponse<QuestionDTO> questions = questionService.queryQuestions(page, size, categoryId, difficulty, tagId, keyword);
        return ApiResponse.success("查询成功", questions);
    }
    @GetMapping("/question/{id}")
    @Operation(summary = "查询题目详情", description = "获取指定题目的详细信息及关联标签")
    public ApiResponse<QuestionDTO> getQuestionDetail(@PathVariable Integer id) {
        QuestionDTO question = questionService.getQuestionById(id);
        return ApiResponse.success("查询成功", question);
    }
    @PostMapping("/admin/question")
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(summary = "新增题目", description = "创建新的面试题目（仅管理员）")
    public ApiResponse<QuestionDTO> addQuestion(@Valid @RequestBody QuestionDTO question) {
        QuestionDTO created = questionService.createQuestion(question);
        return ApiResponse.success("题目创建成功", created);
    }
    @PutMapping("/admin/question/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(summary = "修改题目", description = "更新指定题目的信息（仅管理员）")
    public ApiResponse<QuestionDTO> updateQuestion(@PathVariable Integer id,
                                                   @Valid @RequestBody QuestionDTO question) {
        QuestionDTO updated = questionService.updateQuestion(id, question);
        return ApiResponse.success("题目更新成功", updated);
    }
}
